package com.xinxing.city.recovery.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.xinxing.city.recovery.R;

import java.util.ArrayList;
import java.util.List;

public class VideoSelAdapter extends LinearLayout implements View.OnClickListener {

    Context context;
    Integer position;

    public VideoSelAdapter(Context co, Integer i, Integer all)  {
        super(co);
        LayoutInflater.from(co).inflate(R.layout.item_set_video,this);

        context = co;
        position = i;

        SharedPreferences sharedPreferences = co.getSharedPreferences("MyPrefs",co.MODE_PRIVATE);
        String nameText = "摄像头"+(i+1);
        String codeText = sharedPreferences.getString("aid","")+"camera_"+(i+1);
        if (i+1 == all) {
            nameText = "环境摄像头";
            codeText = sharedPreferences.getString("aid","")+"camera_even";
        }

        TextView name = findViewById(R.id.name);
        name.setText("摄像头名称:"+nameText);

        TextView code = findViewById(R.id.code);
        code.setText("设备编号:"+codeText);

        if (sharedPreferences.getInt("camera_id",0) == i) {
            this.setBackground(context.getDrawable(R.drawable.btn1));
            name.setTextColor(Color.WHITE);
            code.setTextColor(Color.WHITE);
        } else {
            this.setBackground(context.getDrawable(R.drawable.round14));
        }

        setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("MyPrefs",context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        List<View> siblings = getAllSiblings();
        for (View sibling : siblings) {
            sibling.setBackground(context.getDrawable(R.drawable.round14));
            TextView name1 = sibling.findViewById(R.id.name);
            TextView code1 = sibling.findViewById(R.id.code);
            name1.setTextColor(Color.BLACK);
            code1.setTextColor(Color.BLACK);
        }

        this.setBackground(context.getDrawable(R.drawable.btn1));
        TextView name = findViewById(R.id.name);
        TextView code = findViewById(R.id.code);
        name.setTextColor(Color.WHITE);
        code.setTextColor(Color.WHITE);

        editor.putInt("camera_id",position);
        editor.apply();
    }

    public List<View> getAllSiblings() {
        LinearLayout parentLayout = (LinearLayout) getParent();
        List<View> siblings = new ArrayList<>();

        for (int i = 0; i < parentLayout.getChildCount(); i++) {
            View child = parentLayout.getChildAt(i);
            if (child != this) {
                siblings.add(child);
            }
        }

        return siblings;
    }
}
